package com.ldxiwxr.common.utils;


import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.ldxiwxr.common.common.MedicineIdentify;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


import java.util.HashMap;
import java.util.Map;

import static com.ldxiwxr.common.constant.MedicineApiConstant.*;
import static com.ldxiwxr.common.constant.MedicineIdentifyConstant.APP_CODE;
import static com.ldxiwxr.common.constant.MedicineIdentifyConstant.MEDICINE_IDENTIFY_API;

/**
 * 草药识别工具类
 * @author SuBanxia
 */
public class MedicineIdentifyUtils {

    /**
     * 通过上传图片获取草药名称
     * @param file 图片
     * @return 草药名称
     * @throws IOException IO异常
     */
    public static MedicineIdentify getMedicineIdentify(MultipartFile file) throws IOException {
        //判断文件是否为空
        if (file == null){
            return null;
        }

        //调用工具类，生成图片的base64码
        String base64 = FileUtils.loadFileAsBase64(file);

        //发送POST请求获取获取返回的对应的json对象
        try {
            String rspStr = HttpUtil.createPost(MEDICINE_IDENTIFY_API)
                    .header("Authorization", "APPCODE " + APP_CODE)
                    .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                    .form("image", base64)
                    .form("baike", 1)
                    .execute()
                    .body();
            //判断返回对象是否为空
            if (StringUtils.isEmpty(rspStr)) {
                return null;
            }
            //读取获取到的内容
            JSONObject json = new JSONObject(rspStr);
            JSONArray result = json.getJSONArray("result");
            //获取读取到的第一条记录
            JSONObject object = result.getJSONObject(0);

            //创建对应的识别结果对象
            MedicineIdentify medicineIdentify = new MedicineIdentify();
            medicineIdentify.setName(object.getStr("name"));
            medicineIdentify.setBaikeUrl(object.getJSONObject("baike_info").getStr("baike_url"));
            medicineIdentify.setImageUrl(object.getJSONObject("baike_info").getStr("image_url"));
            medicineIdentify.setDescription(object.getJSONObject("baike_info").getStr("description"));

            return medicineIdentify;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
